<template>
  <div class="relative">
    <!-- 标签 -->
    <label v-if="label" :for="id" class="block text-sm font-medium mb-2 text-text-primary">
      {{ label }}
      <span v-if="required" class="text-red-500 ml-1 font-bold">*</span>
    </label>

    <!-- 下拉框容器 -->
    <div class="relative">
      <!-- 选择框 -->
      <button
        :id="id"
        ref="selectRef"
        type="button"
        :class="selectClasses"
        :style="{ borderRadius: '8px !important' }"
        :disabled="disabled"
        @click="toggleDropdown"
        @blur="handleBlur"
        @keydown="handleKeydown"
        :aria-expanded="isOpen"
        :aria-haspopup="true"
        :aria-labelledby="label ? `${id}-label` : undefined"
      >
        <!-- 显示选中的值或占位符 -->
        <span 
          :class="[
            'flex-1 text-left truncate',
            modelValue ? 'text-text-primary' : 'text-text-muted'
          ]"
        >
          {{ displayValue || placeholder }}
        </span>

        <!-- 下拉箭头 -->
        <svg
          class="w-4 h-4 transition-transform duration-200"
          :class="isOpen ? 'rotate-180' : ''"
          fill="none"
          stroke="currentColor"
          viewBox="0 0 24 24"
        >
          <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 9l-7 7-7-7" />
        </svg>
      </button>

      <!-- 下拉选项 -->
      <Transition
        enter-active-class="transition ease-out duration-200"
        enter-from-class="opacity-0 scale-95"
        enter-to-class="opacity-100 scale-100"
        leave-active-class="transition ease-in duration-150"
        leave-from-class="opacity-100 scale-100"
        leave-to-class="opacity-0 scale-95"
      >
        <div
          v-if="isOpen"
          ref="dropdownRef"
          class="absolute z-50 w-full mt-1 bg-background-800 border border-background-600 rounded-lg !rounded-lg shadow-lg max-h-60 overflow-auto"
          :style="{ borderRadius: '8px !important' }"
        >
          <!-- 搜索框（如果启用） -->
          <div v-if="searchable" class="p-2 border-b border-background-600">
            <input
              ref="searchInput"
              v-model="searchQuery"
              type="text"
              class="w-full px-3 py-2 text-sm bg-background-700 border border-background-600 rounded-lg !rounded-lg text-text-primary placeholder-text-muted focus:outline-none focus:ring-2 focus:ring-primary-500 focus:border-transparent"
              :style="{ borderRadius: '8px !important' }"
              placeholder="搜索选项..."
              @keydown.escape="closeDropdown"
            />
          </div>

          <!-- 选项列表 -->
          <div class="py-1">
            <div
              v-for="option in filteredOptions"
              :key="getOptionValue(option)"
              :class="[
                'px-3 py-2 text-sm cursor-pointer transition-colors',
                isOptionSelected(option)
                  ? 'bg-primary-600 text-white'
                  : 'text-text-primary hover:bg-background-700'
              ]"
              @click="selectOption(option)"
              @mouseenter="hoveredIndex = filteredOptions.indexOf(option)"
            >
              {{ getOptionLabel(option) }}
            </div>

            <!-- 无选项提示 -->
            <div
              v-if="filteredOptions.length === 0"
              class="px-3 py-2 text-sm text-text-muted text-center"
            >
              {{ searchable && searchQuery ? '没有找到匹配的选项' : '暂无选项' }}
            </div>
          </div>
        </div>
      </Transition>
    </div>

    <!-- 错误信息 -->
    <p v-if="error" class="mt-1 text-sm text-error">{{ error }}</p>
  </div>
</template>

<script setup lang="ts">
import { computed, nextTick, onMounted, onUnmounted, ref, watch } from 'vue'

interface Option {
  label: string
  value: any
  disabled?: boolean
}

interface Props {
  modelValue?: any
  options?: (Option | string | number)[]
  label?: string
  placeholder?: string
  disabled?: boolean
  required?: boolean
  error?: string
  size?: 'sm' | 'md' | 'lg'
  variant?: 'default' | 'outline' | 'filled'
  searchable?: boolean
  clearable?: boolean
  multiple?: boolean
  id?: string
}

const props = withDefaults(defineProps<Props>(), {
  placeholder: '请选择...',
  disabled: false,
  required: false,
  size: 'md',
  variant: 'default',
  searchable: false,
  clearable: false,
  multiple: false,
  id: () => `select-${Math.random().toString(36).substr(2, 9)}`
})

const emit = defineEmits<{
  'update:modelValue': [value: any]
  'change': [value: any]
  'focus': [event: FocusEvent]
  'blur': [event: FocusEvent]
}>()

// 响应式状态
const isOpen = ref(false)
const searchQuery = ref('')
const hoveredIndex = ref(-1)
const selectRef = ref<HTMLButtonElement>()
const dropdownRef = ref<HTMLDivElement>()
const searchInput = ref<HTMLInputElement>()

// 处理选项数据
const normalizedOptions = computed(() => {
  if (!props.options) return []
  
  return props.options.map(option => {
    if (typeof option === 'string' || typeof option === 'number') {
      return { label: String(option), value: option }
    }
    return option
  })
})

// 过滤选项（支持搜索）
const filteredOptions = computed(() => {
  if (!props.searchable || !searchQuery.value) {
    return normalizedOptions.value
  }
  
  return normalizedOptions.value.filter(option => 
    option.label.toLowerCase().includes(searchQuery.value.toLowerCase())
  )
})

// 显示值
const displayValue = computed(() => {
  if (!props.modelValue) return ''
  
  if (props.multiple && Array.isArray(props.modelValue)) {
    return props.modelValue.map(value => {
      const option = normalizedOptions.value.find(opt => opt.value === value)
      return option?.label || value
    }).join(', ')
  }
  
  const option = normalizedOptions.value.find(opt => opt.value === props.modelValue)
  return option?.label || props.modelValue
})

// 样式类
const selectClasses = computed(() => {
  const baseClasses = [
    'w-full flex items-center justify-between text-sm font-medium transition-all duration-200',
    'focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-offset-background-900',
    'disabled:opacity-50 disabled:cursor-not-allowed'
  ]

  const sizeClasses = {
    sm: 'px-2 py-1.5 text-xs',
    md: 'px-3 py-2 text-sm',
    lg: 'px-4 py-3 text-base'
  }

  const variantClasses = {
    default: [
      'bg-background-800 border border-background-600 rounded-lg !rounded-lg',
      'hover:bg-background-700 hover:border-background-500',
      'focus:ring-primary-500 focus:border-primary-500'
    ],
    outline: [
      'bg-transparent border border-background-600 rounded-lg !rounded-lg',
      'hover:bg-background-800 hover:border-background-500',
      'focus:ring-primary-500 focus:border-primary-500'
    ],
    filled: [
      'bg-background-700 border border-background-600 rounded-lg !rounded-lg',
      'hover:bg-background-600 hover:border-background-500',
      'focus:ring-primary-500 focus:border-primary-500'
    ]
  }

  const errorClasses = props.error ? 'border-error focus:ring-error' : ''

  return [
    ...baseClasses,
    sizeClasses[props.size],
    variantClasses[props.variant],
    errorClasses
  ].join(' ')
})

// 获取选项值
const getOptionValue = (option: Option) => {
  return option.value
}

// 获取选项标签
const getOptionLabel = (option: Option) => {
  return option.label
}

// 检查选项是否被选中
const isOptionSelected = (option: Option) => {
  if (props.multiple && Array.isArray(props.modelValue)) {
    return props.modelValue.includes(option.value)
  }
  return props.modelValue === option.value
}

// 切换下拉框
const toggleDropdown = () => {
  if (props.disabled) return
  
  isOpen.value = !isOpen.value
  
  if (isOpen.value) {
    nextTick(() => {
      if (props.searchable && searchInput.value) {
        searchInput.value.focus()
      }
    })
  }
}

// 选择选项
const selectOption = (option: Option) => {
  if (option.disabled) return
  
  let newValue: any
  
  if (props.multiple) {
    const currentValues = Array.isArray(props.modelValue) ? props.modelValue : []
    const optionValue = option.value
    
    if (currentValues.includes(optionValue)) {
      newValue = currentValues.filter(v => v !== optionValue)
    } else {
      newValue = [...currentValues, optionValue]
    }
  } else {
    newValue = option.value
    closeDropdown()
  }
  
  emit('update:modelValue', newValue)
  emit('change', newValue)
}

// 关闭下拉框
const closeDropdown = () => {
  isOpen.value = false
  searchQuery.value = ''
  hoveredIndex.value = -1
}

// 处理失焦
const handleBlur = (event: FocusEvent) => {
  // 延迟关闭，以便点击选项时不会立即关闭
  setTimeout(() => {
    if (!dropdownRef.value?.contains(event.relatedTarget as Node)) {
      closeDropdown()
    }
  }, 100)
  
  emit('blur', event)
}

// 处理键盘事件
const handleKeydown = (event: KeyboardEvent) => {
  if (!isOpen.value) {
    if (event.key === 'Enter' || event.key === ' ') {
      event.preventDefault()
      toggleDropdown()
    }
    return
  }
  
  switch (event.key) {
    case 'Escape':
      event.preventDefault()
      closeDropdown()
      selectRef.value?.focus()
      break
    case 'ArrowDown':
      event.preventDefault()
      if (hoveredIndex.value < filteredOptions.value.length - 1) {
        hoveredIndex.value++
      }
      break
    case 'ArrowUp':
      event.preventDefault()
      if (hoveredIndex.value > 0) {
        hoveredIndex.value--
      }
      break
    case 'Enter':
      event.preventDefault()
      if (hoveredIndex.value >= 0 && hoveredIndex.value < filteredOptions.value.length) {
        selectOption(filteredOptions.value[hoveredIndex.value])
      }
      break
  }
}

// 点击外部关闭下拉框
const handleClickOutside = (event: MouseEvent) => {
  if (selectRef.value && !selectRef.value.contains(event.target as Node) &&
      dropdownRef.value && !dropdownRef.value.contains(event.target as Node)) {
    closeDropdown()
  }
}

// 监听搜索查询变化
watch(searchQuery, () => {
  hoveredIndex.value = -1
})

// 监听选项变化，重置搜索
watch(() => props.options, () => {
  searchQuery.value = ''
})

// 生命周期
onMounted(() => {
  document.addEventListener('click', handleClickOutside)
})

onUnmounted(() => {
  document.removeEventListener('click', handleClickOutside)
})
</script>
